<script>
  export default {
    onLaunch() {
      // #ifdef APP-PLUS
      plus.push.setAutoNotification(true);
      const _handlePush = ({ payload }) => {
        try {
          // 携带自定义信息跳转应用页面
          uni.navigateTo({
            url: `/pages/postBar?id=${JSON.parse(payload).id}`,
          });
        } catch (e) {
          uni.showToast({ title: e.errMsg, icon: "none" });
        }
      };
      // 事件处理
      plus.push.addEventListener("click", _handlePush);
      plus.push.addEventListener("receive", _handlePush);

      // #endif

      this.checkVersion();
    },
    methods: {
      async checkVersion() {
        // #ifdef MP
        const { onCheckForUpdate, onUpdateReady, onUpdateFailed, applyUpdate } =
          uni.getUpdateManager();

        onCheckForUpdate(({ hasUpdate }) => {
          /* Callback after requesting new version information */
          hasUpdate && uni.clearStorage();
        });

        onUpdateReady((res) => {
          uni.showModal({
            title: "Update Tips",
            content:
              "The new version is ready. Do you want to restart the application?",
            success: ({ confirm }) => confirm && applyUpdate(),
          });
        });

        onUpdateFailed((res) => {
          uni.showToast({
            title: "Failed to download the new version. Please try again later.",
            icon: "none",
          });
        });
        // #endif

        // #ifdef APP-PLUS
        uni.fetch("/api/version/check_version", {
          method: "GET",
          data: {
            platform: uni.getSystemInfoSync().platform,
            version: plus.runtime.version,
          },
          success: async (data) => {
            const [showModalFail, showModalRes] = await uni.showModal({
              title: "已发现更新",
              content: data.description,
              showCancel: Boolean(+data.forceUpdate),
              confirmText: "立即更新",
            });

            if (showModalFail || showModalRes.cancel) return;

            if (uni.getSystemInfoSync().platform === "ios") {
              plus.runtime.openURL(data.upgradeUrl);
              return;
            }

            const showLoading = plus.nativeUI.showWaiting("开始下载...");

            const downloadTask = uni.downloadFile({
              url: data.upgradeUrl,
              success: ({ tempFilePath }) => {
                showLoading.setTitle("正在安装...");

                plus.runtime.install(
                  tempFilePath,
                  {},
                  (e) => {
                    plus.nativeUI.closeWaiting();
                    uni.showModal({
                      title: "更新完成",
                      content: "新版本需要重启APP",
                      confirmText: "立即重启",
                      showCancel: false,
                      success: plus.runtime.restart,
                    });
                  },
                  (error) => {
                    plus.nativeUI.closeWaiting();
                    uni.showToast({ title: "安装失败", icon: "none" });
                  }
                );
              },
              fail() {
                uni.showToast({ title: "下载失败", icon: "none" });
              },
            });

            downloadTask.onProgressUpdate(
              ({ progress, totalBytesWritten, totalBytesExpectedToWrite }) =>
                showLoading.setTitle(
                  `正在下载(${(totalBytesWritten / 1024 ** 2).toFixed(2)}MB/${(
                    totalBytesExpectedToWrite /
                    1024 ** 2
                  ).toFixed(2)}MB)	${progress}%`
                )
            );
          },
        });
        // #endif
      },
    },
  };
</script>

<style>
  @import url(static/css/common.css);
  @import url(static/css/reset.css);

  .color-4388e7 {
    color: #4388e7;
  }

  .color-abbcd7 {
    color: #abbcd7;
  }

  .color-5482bd {
    color: #5482bd;
  }

  .color-8f9aa8 {
    color: #8f9aa8;
  }

  .color-1a {
    color: #1a1a1a;
  }

  .color-4371ff {
    color: #4371ff;
  }

  .color-e48100 {
    color: #e48100;
  }

  .color-5b6c98 {
    color: #5b6c98;
  }

  .color-bac4d0 {
    color: #bac4d0;
  }

  .color-fc5260 {
    color: #fc5260;
  }

  .bgc-f2 {
    background-color: #f2f2f2;
  }

  .bgc-fff9ea {
    background-color: #fff9ea;
  }

  .bgc-f7f4fc {
    background-color: #f7f4fc;
  }

  .bgc-8ec5fc {
    background-color: #8ec5fc;
  }

  /* background-color */

  .bgc-f9 {
    background-color: #f9f9f9;
  }

  .bgc-eee {
    background-color: #eee;
  }

  .bgc-fff {
    background-color: #fff;
  }

  .bgc-000 {
    background-color: #000;
  }

  .bgc-ccc {
    background-color: #ccc;
  }

  .bgc-d4 {
    background-color: #d4d4d4;
  }

  .bgc-eb {
    background-color: #ebebeb;
  }
</style>
